package org.jsola.hr.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.jsola.common.DateKit;
import org.jsola.core.Page;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.common.HrLogKit;
import org.jsola.hr.common.NumberKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.IAttendanceMonthlyDAO;
import org.jsola.hr.dto.AttendanceMonthlyAddDTO;
import org.jsola.hr.dto.AttendanceMonthlyUpdateDTO;
import org.jsola.hr.entity.AttendanceMonthlyDO;
import org.jsola.hr.query.AttendanceMonthlyQuery;
import org.jsola.hr.service.IAttendanceMonthlyService;
import org.jsola.hr.vo.AttendanceMonthlyListVO;
import org.jsola.hr.vo.AttendanceMonthlyVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhr
 */
@Service("hrAttendanceMonthlyServiceImpl")
public class AttendanceMonthlyServiceImpl implements IAttendanceMonthlyService {

    @Autowired
    private IAttendanceMonthlyDAO attendanceMonthlyDAO;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public AttendanceMonthlyVO save(AttendanceMonthlyAddDTO attendanceMonthlyAddDTO, TokenUser tokenUser) {
        // 转DO
        AttendanceMonthlyDO attendanceMonthlyDO = attendanceMonthlyAddDTO.to(AttendanceMonthlyDO.class);
        // 保存
        attendanceMonthlyDO = save(attendanceMonthlyDO, tokenUser.getSiteId(), tokenUser.getUserId());
        HrLogKit.logForSave("新增员工考勤月统计", "saveAttendanceMonthly", attendanceMonthlyDO.getId(), tokenUser);
        return attendanceMonthlyDO.to(AttendanceMonthlyVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(AttendanceMonthlyUpdateDTO attendanceMonthlyUpdateDTO, TokenUser tokenUser) {
        //转DO
        AttendanceMonthlyDO attendanceMonthlyDO = attendanceMonthlyUpdateDTO.to(AttendanceMonthlyDO.class);
        HrLogKit.logForUpdate("修改员工考勤月统计", "updateAttendanceMonthly", attendanceMonthlyDO.getId(), tokenUser);
        //根据主键更新，只更新非null值
        return updateByIdSelective(attendanceMonthlyDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... attendanceMonthlyIds) {
        HrLogKit.logForDelete("批量删除员工考勤月统计", "deleteAttendanceMonthlyByIds"
                , Arrays.toString(attendanceMonthlyIds), tokenUser);
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) attendanceMonthlyIds);
    }


    @Override
    public AttendanceMonthlyVO selectById(String attendanceMonthlyId, String siteId) {
        AttendanceMonthlyDO attendanceMonthlyDO = selectDOById(attendanceMonthlyId, siteId);
        if (attendanceMonthlyDO == null) {
            return null;
        }
        return attendanceMonthlyDO.to(AttendanceMonthlyVO.class);
    }

    @Override
    public List<AttendanceMonthlyListVO> select(AttendanceMonthlyQuery attendanceMonthlyQuery, String siteId) {
        List<AttendanceMonthlyDO> attendanceMonthlyDOList = selectDO(attendanceMonthlyQuery, siteId);
        if(CollectionUtils.isEmpty(attendanceMonthlyDOList)) {
            return attendanceMonthlyDOList == null ? null : new ArrayList<>();
        }
        return attendanceMonthlyDOList.stream()
                .map(attendanceMonthlyDO -> attendanceMonthlyDO.to(AttendanceMonthlyListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(AttendanceMonthlyQuery attendanceMonthlyQuery, String siteId) {
        Example example = buildExample(attendanceMonthlyQuery,siteId);
        return attendanceMonthlyDAO.selectCountByExample(example);
    }

    @Override
    public Page<AttendanceMonthlyListVO> selectPage(AttendanceMonthlyQuery attendanceMonthlyQuery, String siteId) {
        Example example = buildExample(attendanceMonthlyQuery,siteId);
        Page<AttendanceMonthlyDO> page = attendanceMonthlyDAO.selectPageByExample(example,
                attendanceMonthlyQuery.getPageNo(),
                attendanceMonthlyQuery.getPageSize());

        return page.to(AttendanceMonthlyListVO.class);
    }

    @Override
    public AttendanceMonthlyDO selectDOById(String attendanceMonthlyId, String siteId) {
        return listById(attendanceMonthlyId, siteId);
    }

    @Override
    public List<AttendanceMonthlyDO> selectDO(AttendanceMonthlyQuery attendanceMonthlyQuery, String siteId) {
        Example example = buildExample(attendanceMonthlyQuery,siteId);
        return attendanceMonthlyDAO.selectByExample(example);
    }


    @Override
    public Page<AttendanceMonthlyVO> getAttendanceMonthlyReportByPage(AttendanceMonthlyQuery attendanceMonthlyQuery, String siteId) {
        PageInfo<AttendanceMonthlyVO> pageInfo= PageHelper.startPage(attendanceMonthlyQuery.getPageNo(),attendanceMonthlyQuery.getPageSize())
                                            .doSelectPageInfo(()-> attendanceMonthlyDAO.getAttendanceMonthlyReport(attendanceMonthlyQuery,siteId));
        return new Page<>(pageInfo.getList(),pageInfo.getPageNum(),pageInfo.getPageSize(), (int) pageInfo.getTotal()) ;
    }

    @Override
    public Workbook downloadAttendanceMonthlyReport(AttendanceMonthlyQuery attendanceMonthlyQuery, String siteId) {
       List<AttendanceMonthlyVO> attendanceMonthlyVOS=  attendanceMonthlyDAO.getAttendanceMonthlyReport(attendanceMonthlyQuery,siteId);

        HSSFWorkbook workbook =new HSSFWorkbook();
        HSSFSheet sheet=workbook.createSheet();
        Object[][] data=new Object[attendanceMonthlyVOS.size()+1][];
        data[0]= new Object[]{"姓名","出勤天数","基本工资","团队提成","业务佣金","缺勤扣款","未打卡扣款","迟到扣款","加班费","补贴","其他扣款"};
        for (int index=0;index<attendanceMonthlyVOS.size();index++){
            AttendanceMonthlyVO attendanceMonthly=attendanceMonthlyVOS.get(index);
            String name =attendanceMonthly.getEmpName();
            Integer workingDays=attendanceMonthly.getWorkingDays();
            BigDecimal attendanceMonthlyBasic = NumberKit.pareMoneyFromFenToYuan(attendanceMonthly.getSalaryBasic(),2,BigDecimal.ROUND_HALF_UP);
            BigDecimal teamCommission =NumberKit.pareMoneyFromFenToYuan(attendanceMonthly.getTeamCommission(),2,BigDecimal.ROUND_HALF_UP);
            BigDecimal businessCommission = NumberKit.pareMoneyFromFenToYuan(attendanceMonthly.getBusinessCommission(),2,BigDecimal.ROUND_HALF_UP);
            BigDecimal absenteeismDed = NumberKit.pareMoneyFromFenToYuan(attendanceMonthly.getAbsenteeismDed(),2,BigDecimal.ROUND_HALF_UP);
            BigDecimal uncheckDed = NumberKit.pareMoneyFromFenToYuan(attendanceMonthly.getUncheckedDed(),2,BigDecimal.ROUND_HALF_UP);
            BigDecimal lateDed = NumberKit.pareMoneyFromFenToYuan(attendanceMonthly.getLateDed(),2,BigDecimal.ROUND_HALF_UP);
            BigDecimal overtimePay = NumberKit.pareMoneyFromFenToYuan(attendanceMonthly.getOvertimePay(),2,BigDecimal.ROUND_HALF_UP);
            BigDecimal subsidy = NumberKit.pareMoneyFromFenToYuan(attendanceMonthly.getSubsidy(),2,BigDecimal.ROUND_HALF_UP);
            BigDecimal othersDed = NumberKit.pareMoneyFromFenToYuan(attendanceMonthly.getOthersDed(),2,BigDecimal.ROUND_HALF_UP);
            Object[] arr={name,workingDays,attendanceMonthlyBasic,teamCommission,businessCommission,absenteeismDed,uncheckDed,lateDed,overtimePay,subsidy,othersDed};
            data[index+1]=arr;
        }

        for(int i = 0; i < data.length; i++) {
            //创建表格行
            HSSFRow row = sheet.createRow(i);
            for (int j = 0; j < data[i].length; j++) {
                //根据表格行创建单元格
                HSSFCell cell = row.createCell(j);
                cell.setCellValue(String.valueOf(data[i][j]));
                if (i==data.length-1){
                    //依据最后一行的列的数据宽度排序
                    sheet.setColumnWidth(j,String.valueOf(data[i][j]).getBytes().length*500+2000);
                }
            }

        }
        return workbook;
    }

    /**
     * 根据查询参数，构建example

     * @param attendanceMonthlyQuery 查询参数
     * @param siteId 所属站点id
     * @return example
     */
    private Example buildExample(AttendanceMonthlyQuery attendanceMonthlyQuery, String siteId) {
        Example example = new Example(AttendanceMonthlyDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        if (attendanceMonthlyQuery.getEmpId() != null) {
            example.and().andLike("empId", "%" + attendanceMonthlyQuery.getEmpId() + "%");
        }
        if (attendanceMonthlyQuery.getNumber() != null) {
            example.and().andLike("number", "%" + attendanceMonthlyQuery.getNumber() + "%");
        }
        if (attendanceMonthlyQuery.getYear() != null) {
            example.and().andLike("year", "%" + attendanceMonthlyQuery.getYear() + "%");
        }
        if (attendanceMonthlyQuery.getMonth() != null) {
            example.and().andLike("month", "%" + attendanceMonthlyQuery.getMonth() + "%");
        }
        if (attendanceMonthlyQuery.getLateTimes() != null) {
            example.and().andEqualTo("lateTimes", attendanceMonthlyQuery.getLateTimes());
        }
        if (attendanceMonthlyQuery.getLateDed() != null) {
            example.and().andEqualTo("lateDed", attendanceMonthlyQuery.getLateDed());
        }
        if (attendanceMonthlyQuery.getLateMinutes() != null) {
            example.and().andEqualTo("lateMinutes", attendanceMonthlyQuery.getLateMinutes());
        }
        if (attendanceMonthlyQuery.getLeaveTimes() != null) {
            example.and().andEqualTo("leaveTimes", attendanceMonthlyQuery.getLeaveTimes());
        }
        if (attendanceMonthlyQuery.getLeaveDed() != null) {
            example.and().andEqualTo("leaveDed", attendanceMonthlyQuery.getLeaveDed());
        }
        if (attendanceMonthlyQuery.getLeaveMinutes() != null) {
            example.and().andEqualTo("leaveMinutes", attendanceMonthlyQuery.getLeaveMinutes());
        }
        if (attendanceMonthlyQuery.getAbsenteeismTimes() != null) {
            example.and().andEqualTo("absenteeismTimes", attendanceMonthlyQuery.getAbsenteeismTimes());
        }
        if (attendanceMonthlyQuery.getAbsenteeismDed() != null) {
            example.and().andEqualTo("absenteeismDed", attendanceMonthlyQuery.getAbsenteeismDed());
        }
        if (attendanceMonthlyQuery.getUncheckedTimes() != null) {
            example.and().andEqualTo("uncheckedTimes", attendanceMonthlyQuery.getUncheckedTimes());
        }
        if (attendanceMonthlyQuery.getUncheckedDed() != null) {
            example.and().andEqualTo("uncheckedDed", attendanceMonthlyQuery.getUncheckedDed());
        }
        if (attendanceMonthlyQuery.getSupplementTimes() != null) {
            example.and().andEqualTo("supplementTimes", attendanceMonthlyQuery.getSupplementTimes());
        }
        if (attendanceMonthlyQuery.getSupplementDed() != null) {
            example.and().andEqualTo("supplementDed", attendanceMonthlyQuery.getSupplementDed());
        }
        if (attendanceMonthlyQuery.getOverallTimes() != null) {
            example.and().andEqualTo("overallTimes", attendanceMonthlyQuery.getOverallTimes());
        }
        if (attendanceMonthlyQuery.getOverallDed() != null) {
            example.and().andEqualTo("overallDed", attendanceMonthlyQuery.getOverallDed());
        }
        if (attendanceMonthlyQuery.getCompanyId() != null) {
            example.and().andEqualTo("companyId", attendanceMonthlyQuery.getCompanyId());
        }
        if (attendanceMonthlyQuery.getOthersDed() != null) {
            example.and().andEqualTo("othersDed", attendanceMonthlyQuery.getOthersDed());
        }
        if (attendanceMonthlyQuery.getOthersDedRemark() != null) {
            example.and().andLike("othersDedRemark", "%" + attendanceMonthlyQuery.getOthersDedRemark() + "%");
        }
        if (attendanceMonthlyQuery.getSocDed() != null) {
            example.and().andEqualTo("socDed", attendanceMonthlyQuery.getSocDed());
        }
        if (attendanceMonthlyQuery.getPfDed() != null) {
            example.and().andEqualTo("pfDed", attendanceMonthlyQuery.getPfDed());
        }
        if (attendanceMonthlyQuery.getPersonTaxDed() != null) {
            example.and().andEqualTo("personTaxDed", attendanceMonthlyQuery.getPersonTaxDed());
        }
        if (attendanceMonthlyQuery.getWorkingDays() != null) {
            example.and().andEqualTo("workingDays", attendanceMonthlyQuery.getWorkingDays());
        }
        if (attendanceMonthlyQuery.getTeamCommission() != null) {
            example.and().andEqualTo("teamCommission", attendanceMonthlyQuery.getTeamCommission());
        }
        if (attendanceMonthlyQuery.getBusinessCommission() != null) {
            example.and().andEqualTo("businessCommission", attendanceMonthlyQuery.getBusinessCommission());
        }
        if (attendanceMonthlyQuery.getOvertimePay() != null) {
            example.and().andEqualTo("overtimePay", attendanceMonthlyQuery.getOvertimePay());
        }
        if (attendanceMonthlyQuery.getSubsidy() != null) {
            example.and().andEqualTo("subsidy", attendanceMonthlyQuery.getSubsidy());
        }
        if (attendanceMonthlyQuery.getStatus() != null) {
            example.and().andEqualTo("status", attendanceMonthlyQuery.getStatus());
        }
        if (attendanceMonthlyQuery.getRemark() != null) {
            example.and().andLike("remark", "%" + attendanceMonthlyQuery.getRemark() + "%");
        }
        if (attendanceMonthlyQuery.getGmtCreateStart() != null &&
                attendanceMonthlyQuery.getGmtCreateEnd() != null) {
            example.and().andBetween("gmtCreate", attendanceMonthlyQuery.getGmtCreateStart(),
                    attendanceMonthlyQuery.getGmtCreateEnd());
        }
        if (attendanceMonthlyQuery.getCreateUserId() != null) {
            example.and().andLike("createUserId", "%" + attendanceMonthlyQuery.getCreateUserId() + "%");
        }
        if (attendanceMonthlyQuery.getGmtModifiedStart() != null &&
                attendanceMonthlyQuery.getGmtModifiedEnd() != null) {
            example.and().andBetween("gmtModified", attendanceMonthlyQuery.getGmtModifiedStart(),
                    attendanceMonthlyQuery.getGmtModifiedEnd());
        }
        if (attendanceMonthlyQuery.getModifiedUserId() != null) {
            example.and().andLike("modifiedUserId", "%" + attendanceMonthlyQuery.getModifiedUserId() + "%");
        }
        // 排序
        ExampleKit.setExampleOrder(example,attendanceMonthlyQuery.getOrders());
        return example;
    }

    @Override
    public Integer getAttendanceMonthlyCount(AttendanceMonthlyQuery attendanceMonthlyQuery, String siteId){
        Example example = new Example(AttendanceMonthlyDO.class);
        example.and()
                .andEqualTo("companyId", attendanceMonthlyQuery.getCompanyId())
                .andEqualTo("year", attendanceMonthlyQuery.getYear())
                .andEqualTo("month", attendanceMonthlyQuery.getMonth())
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        return attendanceMonthlyDAO.selectCountByExample(example);
    }

    @Override
    public List<AttendanceMonthlyVO> getAttendanceMonthlyFileHistory(AttendanceMonthlyQuery attendanceMonthlyQuery, String siteId){
        if(Objects.isNull(attendanceMonthlyQuery.getYear())){
            attendanceMonthlyQuery.setYear(DateKit.getYear(new Date()));
        }
        Example example = buildExample(attendanceMonthlyQuery,siteId);
        List<AttendanceMonthlyDO> attendanceMonthlyDOList = attendanceMonthlyDAO.selectByExample(example);
        if(CollectionUtils.isEmpty(attendanceMonthlyDOList)) {
            return attendanceMonthlyDOList == null ? null : new ArrayList<>();
        }
        return attendanceMonthlyDOList.stream()
                .map(attendanceMonthlyDO -> attendanceMonthlyDO.to(AttendanceMonthlyVO.class))
                .collect(Collectors.toList());
    }
}




